﻿using Helper;
using Helper.Controls;
using Helper.Models;
using System;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Starehe.Views
{
    
    [ObjectPermissionAttribute(SecurityAction.Demand, RequiredPermissionAccess = UserRoles.Guest)]
    public sealed partial  class LoginWindow : CustomWindow
    {
        bool isLoggingIn;
        public LoginWindow()
        {
            isLoggingIn = false;
            InitializeComponent(); 
            this.Closed+=new EventHandler(LoginWindow_Closed);
            FocusManager.SetFocusedElement(this, txtUsr);
        }
       
        private void Login()
        {
            btnLogin.IsEnabled = false;
            isLoggingIn = true;
            bool isValid = DbUtilities.ValidateWindowsUser();
            MessageBox.Show(isValid + "");
            isLoggingIn = false;
            if (isValid)
            {
                CreateMainWindow();
                this.Visibility = System.Windows.Visibility.Collapsed;
                GC.Collect();  
            }
            else
            {
                btnLogin.IsEnabled = true;
                tbInvalid.Visibility = System.Windows.Visibility.Visible;
            }
        }

        public static bool SetCurrentUserRole()
        {
            bool succ = DataAccessHelper.ExecuteNonQuery("SELECT UserID FROM [User].[Users] WHERE ");
            ((App)Application.Current).SetUserRole(UserRoles.User);
            return succ;
        }


        private void LoginWindow_Closed(object sender, EventArgs e)
        {
            if (isLoggingIn)
                return;
            Application.Current.Shutdown();
        }
       
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {           
            this.Cursor = Cursors.Wait;
            Login();
            this.Cursor = Cursors.Arrow;
        }
        private void CreateMainWindow()
        {
            try
            {
                MainWindow mn = new MainWindow();
                mn.IsHitTestVisible = true;
                Application.Current.MainWindow = mn;
                mn.Show();
            }
            catch { }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

       
    }
}
